

import time
import datetime
import pd.datastore as db
import ystockquote as stockSrc


startDate = datetime.date(2013, 1, 1)


def addStock(symbol):
    if not symbol:
        return
    symbol = symbol.upper()

    key = db.Key('Stock', symbol=symbol)
    stocks = db.get(key)
    if [] != stocks:
        return

    try:
        exchange = stockSrc.get_stock_exchange(symbol)
    except Exception, e:
        print e
        return
    if '"N/A"' == exchange:
        return

    stock = Stock(symbol=symbol, exchange=exchange, lastUpdate=str(startDate))
    stock.put()
    return

def getStocks(symbol):
    if not symbol:
        return []
    symbol = symbol.upper()

    key = db.Key('Stock', symbol=symbol)
    return db.get(key)

def getUpdateDate(stock):
    if not stock:
        return startDate

    if None == stock['lastUpdate']:
        return startDate

    stTime = time.strptime(stock['lastUpdate'], '%Y-%m-%d')
    return datetime.date(stTime.tm_year, stTime.tm_mon, stTime.tm_mday)

def getUpdateDateBySymbol(symbol):
    stocks = getStocks(symbol)
    if [] == stocks:
        return startDate

    return getUpdateDate(stocks[0])

def getLocalHistorical(symbol, date=None, start=None, stop=None):
    if not symbol:
        return []
    symbol = symbol.upper()

    if None != date:
        if type(date) == datetime.date:
            date = str(date)
        key = db.Key('HistoricalData', symbol=symbol, date=date)
        return db.get(key)

    key = db.Key('HistoricalData', symbol=symbol)
    historicalData = db.get(key)
    if historicalData:
        historicalData.sort(key=lambda x: x['date'])

    if not start and not stop:
        return historicalData

    if start and stop and start > stop:
        return []

    if type(start) == datetime.date:
        start = str(start)
    if type(stop) == datetime.date:
        stop = str(stop)

    historicalData = [dailyData for dailyData in historicalData if
     (((not start) or (start and start <= dailyData['date'])) and ((not stop) or (stop and dailyData['date'] <= stop)))]

    return historicalData

# update() mean update all
def update(symbol=None):
    if None == symbol:
        key = db.Key('Stock')
    else:
        symbol = symbol.upper()
        key = db.Key('Stock', symbol=symbol)
    stocks = db.get(key)

    today = datetime.date.today()
    for stock in stocks:
        startDate = getUpdateDate(stock)
        if startDate < today:
            historicalData = getHistorical(symbol= stock['symbol'], start=startDate, stop=today)

            for dailyData in historicalData:
                data = HistoricalData(symbol=stock['symbol'], date=dailyData['date'],
                 volume=dailyData['volume'], adjClose=dailyData['adjClose'], open=dailyData['open'],
                 close=dailyData['close'], low=dailyData['low'], high=dailyData['high'])
                data.put()

            s = Stock(**stock)
            s.lastUpdate = str(today)
            s.put()
    return

def getHistorical(symbol, date=None, start=None, stop=None):
    if not symbol:
        return []
    symbol = symbol.upper()

    if None != date:
        start = str(date)
        stop = str(date)
    else:
        if None == start:
            start = startDate

        if None == stop:
            day1 = datetime.timedelta(days=1)
            stop = str(datetime.date.today()-day1)

        if type(start) == datetime.date:
            start = str(start)

        if type(stop) == datetime.date:
            stop = str(stop)

    try:
        hist_dict = stockSrc.get_historical_prices(symbol, start, stop)
    except Exception, e:
        print e
        return []

    historicalData = []
    for date in sorted(hist_dict.iterkeys()):
        dailyData = {}
        dailyData['date'] = date
        dailyData['volume'] = hist_dict[date]['Volume']
        dailyData['adjClose'] = hist_dict[date]['Adj Close']
        dailyData['open'] = hist_dict[date]['Open']
        dailyData['close'] = hist_dict[date]['Close']
        dailyData['low'] = hist_dict[date]['Open']
        dailyData['high'] = hist_dict[date]['Close']
        historicalData.append(dailyData)

    if historicalData:
        historicalData.sort(key=lambda x: x['date'])

    return historicalData

class Stock(db.Model):
    symbol = db.StringProperty(required=True)
    exchange = db.StringProperty()
    lastUpdate = db.StringProperty()

class HistoricalData(db.Model):
    symbol = db.StringProperty(required=True)
    date = db.StringProperty(required=True)
    volume = db.IntegerProperty()
    adjClose = db.FloatProperty()
    open = db.FloatProperty()
    close = db.FloatProperty()
    low = db.FloatProperty()
    high = db.FloatProperty()

class ChartData(db.Model):
    pass


